'use strict';
const db = uniCloud.database();
const memberCode = db.collection('memberCode');
const integral = db.collection('integral');
let uniID = require('uni-id')
exports.main = async (event, context) => {
	uniID = uniID.createInstance({
		context
	})
	let params = event.params || {}
	let payload = {}
	var data_eve = {}
	if (!event.uniIdToken) {
		return {
			code: 403,
			msg: '缺少token'
		}
	}
	payload = await uniID.checkToken(event.uniIdToken, {
		needPermission: true
	})
	if (payload.code && payload.code > 0) {
		return payload
	}
	params.uid = payload.uid
	const {
		userInfo,
	} = await uniID.checkToken(event.uniIdToken, {
		needPermission: true
	})


	let res = {}
	var time = 86400000
	var endTime = new Date().getTime()
	const {
		code
	} = event
	const countRes = await memberCode.where({
		code
	}).count()
	if (countRes.total !== 1) {
		return {
			code: 404,
			msg: '该兑换码无效'
		}
	} else {
		const {
			data
		} = await memberCode.where({
			code
		}).get()
		if (data[0].is_open == 0) {
			return {
				code: 404,
				msg: '该兑换码已被使用'
			}
		} else {
			if (data[0].is_num == 0) {
				const {
					uid,
				} = params
				res = await uniID.updateUser({
					uid,
					number: Number(userInfo.number) + Number(data[0].number),
				});
				const integral_A = await integral.add({
					uid,
					name: "兑换码兑换积分",
					color: 'blue--dark',
					integral: '+' + String(data[0].number),
					time: new Date().getTime()
				})
				await memberCode.where({
					code
				}).update({
					is_open: 0
				})
				return {
					code: 0,
					msg: '兑换成功'
				}
			} else {
				if (userInfo.endTime) {
					const {
						uid,
					} = params
					res = await uniID.updateUser({
						uid,
						endTime: Number(userInfo.endTime) + Number((time * data[0].number)),
						isvip: 1
					});
				} else {
					const {
						uid,
					} = params
					res = await uniID.updateUser({
						uid,
						endTime: Number(endTime) + Number((time * data[0].number)),
						isvip: 1
					});
				}
				await memberCode.where({
					code
				}).update({
					is_open: 0
				})
				return {
					code: 0,
					msg: '兑换成功'
				}
			}
		}
	}
	//event为客户端上传的参数

	//返回数据给客户端
	return event
};
